package org.example.mallcommon.interceptor;

import cn.hutool.core.util.StrUtil;


import org.example.mallcommon.constant.LoginConstant;
import org.example.mallcommon.projo.User;
import org.example.mallcommon.tool.JwtUtil;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

/**
 * @author 韩先楚
 * 登录拦截器
 */
public class LoginInterception implements HandlerInterceptor {

    private JwtUtil jwtUtil;

    private StringRedisTemplate redisTemplate;

    public LoginInterception(JwtUtil jwtUtil, StringRedisTemplate redisTemplate) {
        this.jwtUtil = jwtUtil;
        this.redisTemplate = redisTemplate;
    }
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取token
        String token = request.getHeader("token");
        //判断token是否有效
    if (StrUtil.isBlank(token))
        return false;
    //获取jwt令牌中的用户信息
        String jwt = redisTemplate.opsForValue().get(LoginConstant.LOGIN_TOKEN + token);
        if (StrUtil.isBlank(jwt))
            return false;
        //解析jwt令牌中的用户信息
        if (!jwtUtil.validateToken(jwt))
            return false;
        User user = jwtUtil.parseToken(jwt);
        if (user == null)
            return false;
        //判断用户是否二次登录
        String uuid = redisTemplate.opsForValue().get(LoginConstant.LOGIN_USER_ID + user.getUsername());
        if (StringUtils.isEmpty(uuid) || !uuid.equals(token))
            return false;
        //判断当前jwt令牌的有效数据 小于一个小时
        if (redisTemplate.getExpire(LoginConstant.LOGIN_TOKEN+token) < 3600)
        {
            //重新生成新的jwt令牌,替换原来的令牌
            String s = jwtUtil.generateToken(user);
            redisTemplate.opsForValue().set(LoginConstant.LOGIN_TOKEN+token,s,6,TimeUnit.HOURS);
            redisTemplate.expire(LoginConstant.LOGIN_USER_ID+user.getUsername(),6, TimeUnit.HOURS);
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }
}
